package com.raspberry.monitor.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.raspberry.monitor.entity.SensorData;
import com.raspberry.monitor.mapper.SensorDataMapper;
import com.raspberry.monitor.service.SensorDataService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class SensorController {
    @Autowired
    SensorDataService sensorDataService;
    @Autowired
    SensorDataMapper sensorDataMapper;

    /**
     * 传感器上报数据
     *
     * @param sensorData
     * @return
     */
    @PostMapping("/postSensorData")
    @Transactional(rollbackFor = Exception.class)
    public R postSensorData(@RequestBody SensorData sensorData) {
        try {
            sensorDataService.save(sensorData);
            return R.ok("保存成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed(e.toString());
        }
    }

    @GetMapping("/getTodaySensorData")
    public R getTodaySensorData() {
        try {
            List<SensorData> tempDataList = sensorDataMapper.listTempDataByPostTimeDesc();
            List<SensorData> smokeDataList = sensorDataMapper.listSmokeDataByPostTimeDesc();
            Map<String, List> resultMap = new HashMap<>();
            resultMap.put("tempSensorData", tempDataList);
            resultMap.put("smokeSensorData", smokeDataList);
            return R.ok(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed("查询失败");
        }
    }
}